package b2.widget.room
{
	import b2.config.*;
	import b2.net.*;
	import b2.player.*;
	import b2.scene.*;
	import b2.scene.fight.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.tab.*;
	
	import com.greensock.*;
	import com.smartfoxserver.v2.core.SFSEvent;
	import com.smartfoxserver.v2.entities.*;
	import com.smartfoxserver.v2.entities.variables.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.text.*;
	import flash.utils.Timer;
	
	public class RoomDialog extends Sprite
	{
		public var campIndex:int;
		public var startButton:BasicButton;
		private var returnButton:BasicButton;
		private var closeButton:BasicButton;
		private var playerGrids:Array;
		private var countDownTimer:Timer;
		private var countDown:int;
		public static const roomPos:Array = [0, 5, 1, 6, 2, 7, 3, 8, 4, 9];
		
		public function RoomDialog(campIndex:int)
		{
			super();
			this.campIndex = campIndex;
			//透明背景
			var bgr:Sprite = new Sprite();
			var gfx:Graphics = bgr.graphics;
			gfx.beginFill(0x000000, 0.01);
			gfx.drawRect(0, 0, BFont.stageWidth, BFont.stageHeight);
			gfx.endFill();
			addChild(bgr);
			//背景图片
			var RoomBgr:Class = ResourceHelper.getInstance().getClassByName("RoomBgr");
			var roomBgr:Sprite = new RoomBgr();
			roomBgr.x = (this.width - roomBgr.width) / 2;
			roomBgr.y = (this.height - roomBgr.height) / 2;
			addChild(roomBgr);
			//线框
			var lineRec:Sprite = new Sprite();
			lineRec.graphics.lineStyle(2, 0x27AAE1);
			lineRec.graphics.drawRoundRect(20, 55, 413, 130, 15, 15);
			lineRec.graphics.drawRoundRect(18, 201, 416, 124, 20, 20);
			lineRec.graphics.drawRoundRect(18, 325, 416, 124, 20, 20);
			lineRec.filters = [new DropShadowFilter(2, 44, 0x000000, 1, 2, 2, 1, 1, false)];
			roomBgr.addChild(lineRec);
			//线框色块
			var rrect:Sprite = new Sprite();
			rrect.graphics.beginFill(0x204B6B);
			rrect.graphics.drawRoundRect(30, 17, 150, 21, 15, 15);
			rrect.graphics.drawRoundRect(20, 55, 413, 130, 15, 15);
			rrect.graphics.endFill();
			rrect.graphics.beginFill(0x27AAE1);
			rrect.graphics.drawRoundRect(20, 203, 413, 25, 15, 15);
			rrect.graphics.drawRoundRect(20, 327, 413, 25, 15, 15);
			rrect.graphics.endFill();
			roomBgr.addChild(rrect);
			//左侧信息
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			//房间号
			var roomNumText:TextField = new TextField();
			roomNumText.selectable = true;
        	roomNumText.autoSize = TextFieldAutoSize.LEFT;
			roomNumText.defaultTextFormat = new TextFormat("微软雅黑", 12, 0xFFFFFF);
			roomNumText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			roomNumText.htmlText = "<font color='#FFFF00'>房间号:</font> " + SmartFoxHelper.getInstance().sfs.lastJoinedRoom.name;
			roomNumText.x = 40;
			roomNumText.y = 17;
			roomBgr.addChild(roomNumText);
			//战役名字
			var campNameText:TextField = new TextField();
			campNameText.selectable = false;
        	campNameText.autoSize = TextFieldAutoSize.LEFT;
			campNameText.defaultTextFormat = new TextFormat("微软雅黑", 17, 0xFFFF00);
			campNameText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			campNameText.text = campConfig.name;
			campNameText.x = (roomBgr.width - campNameText.width) / 2;
			campNameText.y = 58;
			roomBgr.addChild(campNameText);
			//战役详情
			var campDescText:TextField = new TextField();
			campDescText.selectable = false;
			campDescText.wordWrap = true;
			campDescText.multiline = true;
			campDescText.width = 390;
        	campDescText.autoSize = TextFieldAutoSize.LEFT;
			campDescText.defaultTextFormat = new TextFormat("微软雅黑", 14, 0xFFFFFF);
			campDescText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			campDescText.htmlText = campConfig.description;
			campDescText.x = 30;
			campDescText.y = 85;
			roomBgr.addChild(campDescText);
			//比赛战役
			if (campConfig.type == 1)
			{
				//战役说明
				var campDescText2:TextField = new TextField();
				campDescText2.selectable = false;
	        	campDescText2.autoSize = TextFieldAutoSize.CENTER;
				campDescText2.defaultTextFormat = new TextFormat("微软雅黑", 15, 0x00FF00);
				campDescText2.text = "人满后自动开始";
				campDescText2.x = 170;
				campDescText2.y = 160;
				roomBgr.addChild(campDescText2);
			}
			//敌军
			var opponentTitleText:TextField = new TextField();
			opponentTitleText.selectable = false;
        	opponentTitleText.autoSize = TextFieldAutoSize.LEFT;
			opponentTitleText.defaultTextFormat = new TextFormat("微软雅黑", 15, 0xFFFF00);
			opponentTitleText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			opponentTitleText.x = 40;
			opponentTitleText.y = 203;
			roomBgr.addChild(opponentTitleText);
			//我军
			var aliasTitleText:TextField = new TextField();
			aliasTitleText.selectable = false;
        	aliasTitleText.autoSize = TextFieldAutoSize.LEFT;
			aliasTitleText.defaultTextFormat = new TextFormat("微软雅黑", 15, 0xFFFF00);
			aliasTitleText.filters = [new GlowFilter(0x000000, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			aliasTitleText.x = 40;
			aliasTitleText.y = 327;
			roomBgr.addChild(aliasTitleText);
			//开始游戏
			var StartButton:Class = ResourceHelper.getInstance().getClassByName("RoomStartButton");
			startButton = new BasicButton(StartButton, "开始游戏", 40);
			startButton.x = 80;
			startButton.y = 460;
			roomBgr.addChild(startButton);
			//返回按钮
			var ReturnButton:Class = ResourceHelper.getInstance().getClassByName("ButtonBgr0");
			returnButton = new BasicButton(ReturnButton, "离开房间");
			returnButton.x = 320;
			returnButton.y = 470;
			roomBgr.addChild(returnButton);
			returnButton.addEventListener(MouseEvent.CLICK, onCloseButtonClick);
			//关闭按钮
			var CloseButton:Class = ResourceHelper.getInstance().getClassByName("CloseButton");
			closeButton = new BasicButton(CloseButton);
			closeButton.x = roomBgr.width - 44;
			closeButton.y = 14;
			roomBgr.addChild(closeButton);
			closeButton.addEventListener(MouseEvent.CLICK, onCloseButtonClick);
			//显示空房间
			playerGrids = new Array();
			for (var i:int = 0; i < 10; i++)
			{
				var forbidden:Boolean = false;
				//比赛地图
				if (campConfig.type == 1 && i % 5 >= campConfig.recommendedPlayer || 
					campConfig.type == 0 && int(i / 5) == 1 && i % 5 >= campConfig.recommendedPlayer)
					forbidden = true;
				var roomPlayerItem:RoomPlayerItem = new RoomPlayerItem(forbidden);
				roomPlayerItem.x = 30 + (i % 5) * (roomPlayerItem.width + 5);
				roomPlayerItem.y = 231 + int(i / 5) * 124;
				playerGrids.push(roomPlayerItem);
				roomBgr.addChild(roomPlayerItem);
			}
			//比赛战役
			if (campConfig.type == 1)
			{
				opponentTitleText.text = "黑暗帝国";
				aliasTitleText.text = "光明联邦";
				startButton.text = "自动开始";
				startButton.disable = true;
			}
			//普通战役
			else
			{
				opponentTitleText.text = "敌军";
				aliasTitleText.text = "我军";
				//加载敌人
				var enemies:Array = campConfig.getEnemy();
				for (i = 0; i < Math.min(enemies.length, 5); i++)
				{
					(playerGrids[i] as RoomPlayerItem).loadEnemy(enemies[i][0], enemies[i][1]);
				}
				startButton.addEventListener(MouseEvent.CLICK, onStartButtonClick);
			}
			refresh();
			disableExitButton(true);
			TweenLite.delayedCall(3, disableExitButton, [false]);
			SmartFoxHelper.getInstance().sfs.addEventListener(SFSEvent.USER_ENTER_ROOM, onUserEnterRoom);
			SmartFoxHelper.getInstance().sfs.addEventListener(SFSEvent.USER_EXIT_ROOM, onUserExitRoom);
		}

		private function onUserEnterRoom(evt:SFSEvent):void
		{
			var user:User = evt.params.user;
			var room:Room = evt.params.room;
			if (room.isGame)
			{
				refresh();
			}
		}
		
		private function onUserExitRoom(evt:SFSEvent):void
		{
			var user:User = evt.params.user;
			var room:Room = evt.params.room;
			if (room.isGame)
			{
				refresh();
			}
		}

		//刷新所有人的位置
		private function refresh():void
		{
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			//移除所有非敌军玩家
			for (var i:int = 0; i < 10; i++)
			{
				var roomPlayerItem:RoomPlayerItem = playerGrids[i];
				if (roomPlayerItem.occupied && roomPlayerItem.playerId > 0)
				{
					roomPlayerItem.removePlayer();
				}
			}
			var room:Room = SmartFoxHelper.getInstance().sfs.lastJoinedRoom;
			var userIds:Array = new Array();
			//重新加载玩家
			for each (var user:User in room.userList)
			{
				userIds.push(user.id);
			}
			//按玩家id排序
			userIds.sort();
			for each (user in room.userList)
			{
				var userIndex:int = userIds.indexOf(user.id);
				var playerId:int = user.getVariable("playerId").getIntValue();
				var playerName:String = user.getVariable("playerName").getStringValue();
				var tankId:int = user.getVariable("tankId").getIntValue();
				var tankIndex:int = user.getVariable("tankIndex").getIntValue();
				//普通战役
				if (campConfig.type == 0) 
					addPlayer(playerId, playerName, tankId, tankIndex, userIndex + 5);
				//对战战役
				else 
					addPlayer(playerId, playerName, tankId, tankIndex, roomPos[userIndex]);
			}
			//比赛战役, 人满自动开始
			if (campConfig.type == 1 && room.userCount >= room.maxUsers && countDownTimer == null)
			{
				countDownToStart();
			}
		}
		
		private function countDownToStart():void
		{
			disableExitButton(true);
			countDownTimer = new Timer(1000);
			countDownTimer.addEventListener(TimerEvent.TIMER, onTick);
			countDownTimer.start();
			countDown = 5;
		}
		
		private function onTick(event:TimerEvent):void
		{
			countDown--;
			if (countDown <= 0)
			{
				SmartFoxHelper.getInstance().sendGameStart();
				countDownTimer.removeEventListener(TimerEvent.TIMER, onTick);
				countDownTimer.stop();
				countDownTimer = null;
			}
			else
			{
				startButton.text = countDown + "秒后开始";
			}
		}
		
		public function close():void
		{
			if (this.parent != null)
			{
				this.parent.removeChild(this);
			}
		}
		
		private function addPlayer(playerId:int, playerName:String, tankId:int, tankIndex:int, roomPos:int):void
		{
			var roomPlayerItem:RoomPlayerItem = playerGrids[roomPos];
			if (!roomPlayerItem.occupied)
			{
				roomPlayerItem.loadPlayer(playerId, playerName, tankId, tankIndex);
			}
		}
		
		public function removePlayer(playerId:int):void
		{
			for (var i:int = 0; i < 10; i++)
			{
				var roomPlayerItem:RoomPlayerItem = playerGrids[i];
				if (roomPlayerItem.occupied && roomPlayerItem.playerId == playerId)
				{
					roomPlayerItem.removePlayer();
					break;
				}
			}
		}
		
		private function disableExitButton(flag:Boolean):void
		{
			if (flag || countDownTimer == null)
			{
				returnButton.disable = flag;
				closeButton.disable = flag;
			}
		}
		
		private function onCloseButtonClick(event:MouseEvent):void
		{
			if (!returnButton.disable)
			{
				var me:PlayerInfo = PlayerInfoManager.getInstance().me;
				var matchDialog:MatchDialog = WidgetManager.getInstance().getWidget(MatchDialog) as MatchDialog;
				//正在比赛中
				if (me.signUpMatchFlag && matchDialog != null)
					SmartFoxHelper.getInstance().enterMatchSignUpRoom(matchDialog.campIndex, matchDialog.matchIndex);
				else
					SmartFoxHelper.getInstance().joinRoom(SmartFoxHelper.INITIAL_ROOM_NAME);
				close();
			}
		}
		
		private function onStartButtonClick(event:MouseEvent):void
		{
			SmartFoxHelper.getInstance().sendGameStart();
		}
		
	}
}